
<template>
  <div class="createPost-container">
    <div class="createPost-main-container">
      <el-form ref="form" :model="form" :rules="rules" label-width="60px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择">
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="规格">
          <div>

            <div v-for="(property, propertyIndex) in form.properties" :key="propertyIndex" style="margin-bottom: 20px">
              规格名:
              <el-select v-model="property.name" @change="handleChangeProperty(propertyIndex, property.name)" class="property-select" suffix-icon filterable allow-create default-first-option>
                <el-option v-for="item in baseProperties.filter(baseProperty => {return form.properties.map(i=>{return i.name}).indexOf(baseProperty.name)<0})" :key="item.name" :label="item.name" :value="item.name"></el-option>
              </el-select>
              <el-icon @click="removeProperty(propertyIndex)" class="remove-icon"><remove /></el-icon>
              <div style="height: 10px"></div>
              规格值:
              <span v-for="(value, valueIndex) in property.values">
                <el-select @change="handleChangePropertyValue(propertyIndex, valueIndex, property.values[valueIndex])" :ref="'property-' + propertyIndex + '-' + valueIndex" v-model="property.values[valueIndex]" class="property-select" no-data-text="请手动输入值" suffix-icon filterable allow-create default-first-option>
                  <el-option v-for="item in (basePropertyValues[property.name] ? basePropertyValues[property.name].filter(propValue => {return property.values.indexOf(propValue.value) < 0}) : [])" :key="item.value" :label="item.value" :value="item.value"></el-option>
                </el-select>
                <el-icon @click="removePropertyValue(propertyIndex, valueIndex)" class="remove-icon"><remove /></el-icon>
              </span>

              <el-button @click="addPropertyValue(propertyIndex)" style="font-size: 13px; margin-left: 15px"> <el-icon><plus /></el-icon> </el-button>
            </div>

            <div>
              <el-button type="primary" @click="addProperty" :disabled="form.properties.length>=3">添加规格项目</el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="规格明细">
            <el-table :data="skus" class="radius">
              <el-table-column v-for="(property, index) in properties" :key="index" :label="property.name" :prop="'property-' + (index + 1)"></el-table-column>
<!--              <el-table-column v-for="(property, index) in properties" :key="index" :label="property.name" :prop="property.name"></el-table-column>-->
              <el-table-column label="价格(元)">
                <template v-slot="scope"><el-input v-model="scope.row.price"></el-input></template>
              </el-table-column>
              <el-table-column label="库存">
                <template v-slot="scope"><el-input v-model="scope.row.quantity"></el-input></template>
              </el-table-column>
              <el-table-column label="重量">
                <template v-slot="scope"><el-input v-model="scope.row.weight"></el-input></template>
              </el-table-column>
              <el-table-column label="规格编码">
                <template v-slot="scope"><el-input v-model="scope.row.outerId"></el-input></template>
              </el-table-column>
              <el-table-column label="成本价">
                <template v-slot="scope"><el-input v-model="scope.row.costPrice"></el-input></template>
              </el-table-column>
            </el-table>
          <div>
            批量设置：
            <el-button type="text">价格</el-button>
            <el-button type="text">库存</el-button>
            <el-button type="text">重量</el-button>
          </div>
        </el-form-item>

        <el-form-item label="封面">
          <el-upload
            class="image-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeUpload"
          >
            <div v-if="coverPicturePreview">
              <el-image
                class="image"
                :src="coverPicturePreview"
                fit="scale-down">
              </el-image>
              <i class="el-icon-delete image-tools" @click.stop="removeCoverPicture" title="点击删除"></i>
            </div>
            <div v-else class="image-uploader-icon">
              <el-icon size="28"><plus /></el-icon>
            </div>
          </el-upload>
          <input v-model="form.coverPicture" type="hidden">
        </el-form-item>

        <el-form-item label="图片墙">
          <el-upload
            action="#"
            list-type="picture-card"
            multiple
            :limit="5"
            :file-list="form.pictures.filter(i=>!i.delete)"
            :before-upload="beforePictureUpload"
            :on-preview="handlePictureCardPreview"
            :on-remove="handlePictureCardRemove"
            :on-exceed="handleExceed">
            <el-icon><plus /></el-icon>
          </el-upload>
          <el-dialog v-model="picturePreviewDialogVisible">
            <img style="width: 96%" :src="picturePreviewDialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>

        <el-form-item label="链接" prop="link">
          <el-input v-model="form.link"></el-input>
        </el-form-item>

        <el-form-item prop="summary" style="margin-bottom: 30px;" label="摘要">
          <el-input v-model="form.summary" type="textarea" rows="5"></el-input>
        </el-form-item>

        <el-form-item prop="detail" style="margin-bottom: 30px;" label="详情">
          <!-- <Tinymce ref="editor" v-model="form.detail" :height="400" prop="detail" /> -->
          <Tinymce
            ref="detail"
            v-model="form.detail"
            :disabled="false"
            :images-upload-url="upload_api"
            ></Tinymce>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">确定</el-button>
          <el-button @click="onCancel">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import Sortable from "sortablejs"

import { createArticle, getArticle, updateArticle } from '@/api/article.js'
import { getList as fetchCategories } from '@/api/articlecat.js'
import { uploadImage } from '@/api/file'
import { ElMessageBox as MessageBox } from 'element-plus'
import {deepClone} from "@/utils";

const defaultForm = {
  id: undefined,
  title: '',
  categoryId: 1,
  link: '',
  coverPicture: '',
  pictures: [],
  summary: '',
  detail: '',
  properties: []
}

export default {
  name: 'ArticleDetail',
  components: { Tinymce },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      upload_api: window.$config.upload_api,
      coverPicturePreview: '',
      categories: [],

      baseProperties:[
        {id: 1, name: '颜色'},
        {id: 2, name: '尺码'},
        {id: 3, name: '尺寸'}
      ],
      basePropertyValues: {
        '颜色': [
          {id: 1, value: '红色'},
          {id: 2, value: '黄色'},
          {id: 3, value: '蓝色'},
        ],
        '尺码': [
          {id: 11, value: 'S'},
          {id: 12, value: 'M'},
          {id: 13, value: 'L'},
        ],
        '尺寸': [
          {id: 21, value: '4.5'},
          {id: 22, value: '5.1'},
          {id: 23, value: '6.0'},
        ]
      },
      properties: [], // 最终有效的规格项
      skus: [],
      form: {
        pictures: []
      },
      rules: {
        categoryId: [{
          type: 'number',
          required: true,
          message: '请选择分类',
          trigger: 'change'
        }],
        title: [{
          required: true,
          message: '请输入标题',
          trigger: 'blur'
        }]
      },
      picturePreviewDialogVisible: false,
      picturePreviewDialogImageUrl: ''
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      getArticle(id).then(data => {
        data.pictures.forEach(e => e.uid = e.id) // fixed 拖拽排序动画效果
        this.form = data
        this.coverPicturePreview = data.coverPicture
      })
    } else {
      this.form = Object.assign({}, defaultForm)
    }

    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
    // 获取分类列表
    fetchCategories().then(data => {
      this.categories = data
    })
  },
  mounted() {
    this.dragSortPictures()
  },
  methods: {
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.isEdit) {
            const id = this.$route.params && this.$route.params.id
            updateArticle(id, this.form).then(() => {
              this.$message({
                title: '成功',
                message: '更新成功！',
                type: 'success'
              })
            }).catch(() => {
              this.$message({
                title: '提示',
                message: '更新失败！',
                type: 'error'
              })
            })
          } else {
            createArticle(this.form).then(() => {
              this.form = Object.assign({}, defaultForm)
              this.$refs.form.resetFields()
              this.coverPicturePreview = ''
              this.$message({
                title: '成功',
                message: '添加成功！',
                type: 'success'
              })
            })
          }
        }
      })
    },
    onCancel() {
      this.$router.go(-1) // 返回上一层
    },

    beforeUpload(file) {
      const formData = new FormData()
      formData.append('file', file)
      uploadImage(formData).then((data) => {
        this.coverPicturePreview = data.location
        this.form.coverPicture = data.location
      })
      return false
    },
    removeCoverPicture() {
      this.coverPicturePreview = ''
      this.form.coverPicture = ''
    },

    beforePictureUpload(file) {
      const formData = new FormData()
      formData.append('file', file)
      uploadImage(formData).then((data) => {
        if (!this.form.pictures) {
          this.form.pictures = []
        }
        this.form.pictures.push({
          url: data.location,
          delete: false
        })
      })
      return false
    },
    handlePictureCardPreview(file) {
      this.picturePreviewDialogImageUrl = file.url
      this.picturePreviewDialogVisible = true
    },
    handlePictureCardRemove(file) {
      const tmpPics = []
      this.form.pictures.forEach((element) => {
        if (element.uid === file.uid) {
          if (element.id) {
            element.delete = true
            tmpPics.push(element)
          }
        } else {
          tmpPics.push(element)
        }
      })
      this.form.pictures = tmpPics

      // this.form.pictures = fileList
    },
    handleExceed() {
      MessageBox.alert('最多只能上传5长图片！', '', {
        type: 'warning'
      })
    },
    dragSortPictures() {
      Sortable.create(this.$el.querySelector('.el-upload-list--picture-card'), {
        onEnd: e => {
          console.log(this.form.pictures)
          if (e.oldIndex === e.newIndex) return
          // 重排图片
          const pictures = deepClone(this.form.pictures)
          // 取出移动的项目
          const movePicture = pictures.splice(e.oldIndex, 1)[0];
          // 插入移动的项目
          pictures.splice(e.newIndex, 0, movePicture)
          // 重新计算 sortId
          for (let i = 0; i < pictures.length; i++) {
            pictures[i].sortId = i
          }
          this.form.pictures = pictures
        }
      })
    },

    // 添加规格项
    addProperty() {
      this.form.properties.push({
        name: '',
        values: ['']
      })
    },
    // 删除规格项目
    removeProperty(index) {
      this.form.properties.splice(index, 1)
      this.generateSkus()
    },
    // 删除规格值
    removePropertyValue(propertyIndex, valueIndex) {
      if (this.form.properties[propertyIndex].values.length <= 1) {
        this.$alert('请至少保留一个规格值!\n您可以通过删除规格名来删除规格项目!', '提示', {type: 'warning'})
        return
      }
      this.form.properties[propertyIndex].values.splice(valueIndex, 1)
      this.generateSkus()
    },
    // 添加规格值
    addPropertyValue(propertyIndex) {
      this.form.properties[propertyIndex].values.push('')
      this.$nextTick(() => {
        this.$refs['property-' + propertyIndex + '-' + (this.form.properties[propertyIndex].values.length - 1)][0].focus()
      })
    },
    // 规格名变动
    handleChangeProperty(propertyIndex, newName) {
      console.log(propertyIndex, newName)
      this.generateSkus()
    },
    // 规格值变动
    handleChangePropertyValue(propertyIndex, valueIndex, newValue) {
      if(this.form.properties[propertyIndex].values.filter(value => {return value == newValue}).length > 1) {
        this.$alert('规格值 ' + newValue + ' 已经存在！', '提示', {type: 'warning'})
        // 将值置空
        this.form.properties[propertyIndex].values[valueIndex] = ''
      }
      console.log(propertyIndex, valueIndex, newValue)
      this.generateSkus()
    },
    generateSkus() {
      /**
       * 根据现有数据生成sku列表
       * @param skuList
       * @param prop 当前的属性
       * @returns {[]|*}
       */
      function generateSkuList(skuList, prop) {
        if (skuList.length == 0) {
          // 属性名空的直接跳过
          if (!prop.name) return skuList

          prop.values.forEach(value => {
            // 忽略空的属性值
            if (value.trim() == '') return

            let tmpSku = {
              price: '',
              weight: '',
              quantity: '',
              outerId: '',
              costPrice: ''
            }
            tmpSku['property-' + level] = value
            // tmpSku[prop.name] = value
            const tmpSkuProperties = {}
            tmpSkuProperties[prop.name] = value
            tmpSku.properties = tmpSkuProperties

            skuList.push(tmpSku)
          })
          return skuList
        }

        let tmps2 = []
        skuList.forEach(row => {
          prop.values.forEach(value => {
            // 忽略空的属性值
            if (value.trim() == '') return

            let tmpRow = deepClone(row)
            tmpRow['property-' + level] = value
            // tmpRow[prop.name] = value
            tmpRow.properties[prop.name] = value
            tmps2.push(tmpRow)
          })
        })

        return tmps2
      }

      // 如果有属性名没填，或属性值少于一个的就不操作
      for (const i in this.form.properties) {
        const property = this.form.properties[i]
        if (property.name.trim() == '') return
        if (property.values.filter(o => {return o.trim() != ''}).length < 1) return
      }

      // console.log(this.skus)

      let level = 0
      let tmps = [];
      const properties = [];
      this.form.properties.forEach(property => {
        // 忽略空的属性名
        if (property.name.trim() == '') return

        level ++
        let tmpProp = deepClone(property)
        tmpProp.values = tmpProp.values.filter(o => {return o.trim() != ''})
        if (tmpProp.values.length > 0) {

          properties.push(property)
          tmps = generateSkuList(tmps, property)
        }
      })
      this.properties = properties
      // console.log(tmps)

      // 将老的数据复制到新的上面来
      this.skus.forEach(sku => {
        for (const o in tmps) {
          if (JSON.stringify(sku.properties) == JSON.stringify(tmps[o].properties)) {
            // console.log('匹配到了老数据')
            tmps[o] = sku
          }
        }
      })

      this.skus = tmps
    }

  }
}
</script>

<style scoped>
.line {
  text-align: center;
}
</style>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .property-select {
    width: 100px;
    margin-left: 15px;
  }
  .remove-icon {
    cursor:pointer;font-size: 14px;margin-top: 3px; margin-left: -20px;
  }

  .createPost-main-container {
    padding: 20px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-article {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
<style>
.image-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.image-uploader .el-upload:hover {
  border-color: #409eff;
}
.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 146px;
  height: 146px;
  line-height: 146px;
  text-align: center;
}
.image-tools {
  color: #8c939d;
  width: 28px;
  font-size: 28px;
  display: block;
  position: absolute;
  right: 0px;
  top: 0px;
}
.image-tools:hover {
  color: #409eff;
}
.image {
  width: 148px;
  height: 148px;
  margin-bottom: -10px;
}
</style>
